package ie.nolantech.gpsg;

import ie.nolantech.chart.Chart;

import org.achartengine.ChartFactory;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ResultViewer extends ListActivity {
	static final String TAG = "ResultViewer";
	Cursor c;
	SimpleCursorAdapter mSca;
	TextView mTxtCount;
	TextView mKmphLimit;
	
	GpsHelper mHelper;
	
	int kmphGoal;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.result_viewer);
		
		 mHelper = new GpsHelper(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		
		SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
		try{
			kmphGoal = Integer.parseInt(prefs.getString("kmph_limit", "30"));
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		refreshCursor();

		Button btnChart = (Button)findViewById(R.id.btn_show_chart);
		
		btnChart.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Cursor c = null;
				try {
					c = mHelper.getEntriesOverGoal(kmphGoal);

					Intent intent = ChartFactory.getLineChartIntent(
							ResultViewer.this,
							Chart.getResultDataset(c, "Time over goal", "Seconds"),
							Chart.getDemoRenderer());
					startActivity(intent);
				} finally {
					if (c != null)
						c.close();
				}

			}
		});
	}

	private void refreshCursor() {
		mTxtCount = (TextView) findViewById(R.id.txt_count_val);
		mKmphLimit = (TextView) findViewById(R.id.txt_limit_val);
		
		mKmphLimit.setText(""+kmphGoal);
		
		

		c = mHelper.getEntriesOverGoal(kmphGoal);

		if (c != null) {
			mTxtCount.setText("" + c.getCount());
			Log.d(TAG, "Cursor size" + c.getCount());

			startManagingCursor(c);

			mSca = new SimpleCursorAdapter(this, R.layout.db_row, c,
					new String[] { "_id", "lat", "lon", "speed", "date_done",
							"value_type" }, new int[] { R.id.txt_index,
							R.id.txt_col1, R.id.txt_col2, R.id.txt_col3,
							R.id.txt_col4, R.id.txt_value_type });

			setListAdapter(mSca);
		} else {
			Log.d(TAG, "The cursor was null");
		}
		registerForContextMenu(getListView());

	}

	// @Override
	// public boolean onContextItemSelected(MenuItem item) {
	// // TODO Auto-generated method stub
	// return super.onContextItemSelected(item);
	// }

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// Cursor c = (Cursor) l.getItemAtPosition(position);
		// final int _id = c.getInt(c.getColumnIndex("_id"));
		final String _id = ((TextView) v.findViewById(R.id.txt_index))
				.getText().toString();
		final String dateDone = ((TextView) v.findViewById(R.id.txt_col3))
				.getText().toString();

		AlertDialog.Builder builder = new AlertDialog.Builder(ResultViewer.this);
		builder.setMessage(
				"Confirm delete[date:" + dateDone + ":id" + _id + "]")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								GpsHelper helper = new GpsHelper(
										ResultViewer.this);
								helper.deletePoint(Integer.parseInt(_id));
								// mSca.notifyDataSetChanged();
								// onContentChanged();
								refreshCursor();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	protected void onPause() {
		if (c != null) {
			c.close();
		}
		super.onPause();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Cursor c = (Cursor) l.getItemAtPosition(position);
		// final int _id = c.getInt(c.getColumnIndex("_id"));
		String lat = c.getString(c.getColumnIndex("lat"));
		String lon = c.getString(c.getColumnIndex("lon"));
		// String dateDone = c.getString(c.getColumnIndex("date_done"));
		super.onListItemClick(l, v, position, id);
		Intent i = new Intent(this, Map.class);
		i.putExtra("lat", lat);
		i.putExtra("lon", lon);
		startActivity(i);

	}

}
// LayoutInflater li = (LayoutInflater) this
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//
// TableLayout tl = (TableLayout) findViewById(R.id.table_layout1);
// TableRow tr = (TableRow) li.inflate(R.layout.db_row, null);
// TextView col3 = (TextView) tr.findViewById(R.id.txtCol3);
// col3.setText("" + dateDone);
//
// tl.addView(tr);

